package com.ty.xiaoyu.service.impl;

import com.ty.xiaoyu.entity.SearchHistory;
import com.ty.xiaoyu.exception.SearchHistoryOperationException;
import com.ty.xiaoyu.service.SearchHistoryService;
import com.ty.xiaoyu.util.MyTimeUtil;
import com.ty.xiaoyu.util.PageCalculatorUtil;
import com.ty.xiaoyu.util.RandomIdUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SearchHistoryServiceImpl extends BaseService implements SearchHistoryService {

    @Override
    public void addSearchHistory(SearchHistory history) throws SearchHistoryOperationException {
        history.setHistoryId(RandomIdUtil.getId());
        history.setCreatTime(MyTimeUtil.nowTime());
        history.setLastUpdateTime(MyTimeUtil.nowTime());
        history.setHistoryState(1);
        Integer state = searchHistoryMapper.insertSearchHistory(history);
        if (state <= 0) {
            throw new SearchHistoryOperationException("添加搜索记录失败");
        }
    }

    @Override
    public List<SearchHistory> getSearchHistoryByUserId(Integer pageIndex, Integer pageSize, String userId) throws SearchHistoryOperationException {
        Integer rowIndex = PageCalculatorUtil.calculateRowIndex(pageIndex, pageSize);
        List<SearchHistory> historyList = searchHistoryMapper.querySearchHistoryByUserId(rowIndex, pageSize, userId);
        if (historyList == null || historyList.isEmpty()) {
            throw new SearchHistoryOperationException("未找到搜索记录");
        }
        return historyList;
    }

    @Override
    public SearchHistory getSearchHistoryByUserIdAndSearchText(String userId, String searchText) {
        return searchHistoryMapper.querySearchHistoryByUserIdAndSearchText(userId, searchText);
    }

    @Override
    public void updateSearchHistoryByHistory(SearchHistory history) throws SearchHistoryOperationException {
        history.setLastUpdateTime(MyTimeUtil.nowTime());
        Integer state = searchHistoryMapper.updateSearchHistoryByHistory(history);
        if (state <= 0) {
            throw new SearchHistoryOperationException("更新搜索记录失败");
        }
    }

    @Override
    public void deleteAllSearchHistoryByUserId(String userId) throws SearchHistoryOperationException {
        Integer state = searchHistoryMapper.deleteAllSearchHistoryByUserId(userId, MyTimeUtil.nowTime());
        if (state <= 0) {
            throw new SearchHistoryOperationException("删除搜索记录失败");
        }
    }
}
